using LitJson;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;

using WebSocketServer;

public class MyWebSocketServer : WebSocketServer.WebSocketServer
{
    Dictionary<string, object> userInfos = new Dictionary<string, object>();

    override public void OnOpen(WebSocketConnection connection)
    {
        // Here, (string)connection.id gives you a unique ID to identify the client.
        Debug.Log(connection.id);
    }

    override public void OnMessage(WebSocketMessage message)
    {
        // (WebSocketConnection)message.connection gives you the connection that send the message.
        // (string)message.id gives you a unique ID for the message.
        // (string)message.data gives you the message content.
        Debug.Log(message.connection.id);
        Debug.Log(message.id);

        string dataStr = null;
        if (message.data is byte[])
        {
            dataStr = Encoding.UTF8.GetString(message.data as byte[]);
        }
        else
        {
            dataStr = message.data as string;
        }

        Debug.Log(dataStr);

        var json = JsonMapper.ToObject(dataStr);
        var msgID = (string)json["msgID"];

        var msgIds = msgID.Split('.');
        switch (msgIds[0])
        {
            case "login":
                {
                    var userId = (string)json["data"]["uid"];
                    if (userInfos.ContainsKey(userId))
                    {

                    }
                }
                break;
        }

        Debug.LogError(msgID);

        this.SendMessageToClient("asb");

    }

    override public void OnClose(WebSocketConnection connection)
    {
        // Here is the same as OnOpen
        Debug.Log(connection.id);
    }

    public void onConnectionOpened(WebSocketConnection connection)
    {
        Debug.Log("Connection opened: " + connection.id);
    }

    public void onMessageReceived(WebSocketMessage message)
    {
        Debug.Log("Received new message: " + message.data);
    }

    public void onConnectionClosed(WebSocketConnection connection)
    {
        Debug.Log("Connection closed: " + connection.id);
    }
}
